<?php
namespace WebApper\Shortcode;

/*
 * [recordindexphonestaff id='RecordIndexPhoneStaff' posttype=lead fieldset='Group 1' linkedfield='field-id' titlefield='field-id' editor=false adminonly=false]
 *
 */
class RecordIndexPhoneStaff extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'recordindexphonestaff';
	protected $defaults = array(
		'id' => null,		// The unique ID to use for the shortcode. Default: none. Required.
		'usercap' => 'edit_others_posts',	// The minimum user capability required to access the Indextable. OPTIONS: 'logged_out', 'read', 'edit_posts', 'edit_others_posts', 'edit_users', 'edit_pages', 'edit_plugins'. Default 'edit_others_posts'.
		'posttype' => null,					// The cutom post type (ID) to display. Default: none. Required.
		'fieldset' => null,					// The set of fields to include in the indextable. Default: none. Required if 'include' is not specified. You may use one or both.
		'include' => null,					// field-id's of individual fields to include in the indextable. Default: none. Required if 'fieldset' is not specified. You may use one or both.
		'exclude' => null,					// field-id's of individual fields to exclude in the indextable. Default: none.
		'titlefield' => null,				// The field to use for new rocord post titles. Default: none.
		'linkedfield' => null,				// The field to link a record to it's single view. Default: none.
		'editor' => 'true',					// Whether to enable add, edit & delete controls to the indextable. Default: true.
		'widget' => false,					// Whether to display the Tasks as a page widget
		'singleviewurl' => null,			// The record single view URL to to use when a linked field is clicked on. Default: none.
		'tableclasses' => 'table-bordered,table-striped,table-hover,table-condensed',  // Adjusts how the indextable will display. Default: 'table-bordered,table-striped,table-hover,table-condensed'.
		'successsave' => 'Save successful!',			// The message to display upon successful editor save. Default: 'Save successful!'
		'failuresave' => 'Save unsuccessful.',			// The message to display upon unsuccessful editor save. Default: 'Save unsuccessful.'
		'successupdate' => 'Update successful!',		// The message to display upon successful editor update. Default: 'Update successful!'
		'failureupdate' => 'Update unsuccessful.',		// The message to display upon unsuccessful editor update. Default: 'Update unsuccessful.'
		'successdelete' => 'Deletion successful!',		// The message to display upon successful editor deletion. Default: 'Deletion successful!'
		'failuredelete' => 'Deletion unsuccessful.',	// The message to display upon unsuccessful editor deletion. Default: 'Deletion unsuccessful.'
	);

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Get shortcode attributes
			extract( shortcode_atts( $this->defaults, $atts ) );

		// Check for required shortcode attributes
			$msg = $this->has_req_attrs( $atts );
			if ( $msg !== true )
				return $msg;

        // Check if current user has proper privileges
			if ( !$this->user_has_cap( $usercap ) )
				return;

		// Get the fields
			$this->get_fields( $atts );

		// Get the Custom Post Type
			global $current_user; get_currentuserinfo(); // Get the current user object
			$get_posts_args = array( 
				'post_type' => $posttype, 
				'showposts' => 6, 
				'order'=> 'ASC', 
				'orderby' => 'title', 
				'posts_per_page' => -1,
				'meta_query' => array(
					array(
						'key' => 'lead-status',
						'value' => 'Assigned',
						'compare' => '='
					),
					array(
						'key' => 'assigned_to',
						'value' => $current_user->user_login,
						'compare' => '='
					)
				)
			);  // Set query arguments
			$customPostObjsONLY6 = get_posts( $get_posts_args );  // Get the posts
			$get_posts_args = array(
				'post_type' => $posttype,
				'order'=> 'ASC',
				'orderby' => 'title',
				'posts_per_page' => -1,
				'meta_query' => array(
					array(
						'key' => 'lead-status',
						'value' => 'Assigned',
						'compare' => '!='
					),
					array(
						'key' => 'assigned_to',
						'value' => $current_user->user_login,
						'compare' => '='
					)
				)
			);  // Set query arguments
			$customPostObjsALL = get_posts( $get_posts_args );  // Get the posts
			$customPostObjs = array_merge($customPostObjsONLY6, $customPostObjsALL);
			$customPosts = array();
			$tempFields = array();
			foreach ( $customPostObjs as $post ) :  // Foreach post,
				foreach ( $this->fields as $field => $fieldData ) :  // and foreach field,
					$fieldID = $fieldData['field_id'];
					$fieldIDs .= $fieldID . ',';
					$value = get_post_meta( $post->ID, $fieldID, true );  // get the field value
					if ( $this->isSerialized( $value ) ) :  // Possibly unserialize
						$value = unserialize($value);
					endif;
					if ( is_array( $value ) ) :  // Possibly cantonate array in CSV string
						$values = '';
						foreach ( $value as $val )
							$values .= $val . ', ';
						$value = substr(trim($values), 0, -1);
					endif;
					$tempFields[$fieldID] = $value;
				endforeach;
				$customPosts[$post->ID] = $tempFields;
			endforeach;

		// Ouput datatable HTML & Javascript
			$columnIndexCount = 1; // Counter to for getting indexes of columns to be hidden
			echo '<table id="', $id, '_datatable" class="table ', str_replace(",", " ", $tableclasses), '"><thead><tr>';
				echo '<th>web_apper_id</th>';
				foreach ( $this->fields as $fieldID => $fieldData ) :
					echo '<th>', $fieldData['field_name'], '</th>';
					if ( !$fieldData['show_in_table'] )
						$columnsToHide .= $columnIndexCount . ', ';
					$columnIndexCount++;
				endforeach;
			echo '</tr></thead><tbody>';
				foreach ( $customPosts as $postID => $postData ) :
					echo '<tr><td>', $postID, '</td>';
						$linkedFieldCounter = 1;  // Holds the position of the field to be linked. starts at 1 sind the 0 position holds the ID field.
						foreach ( $postData as $customFieldID => $customFieldValue ) :
							if ( $customFieldID == $linkedfield ) :
								echo '<td id="' . $singleviewurl . '?postID=' . $postID . '" class="linked-field">', $customFieldValue, '</td>';
								$linkedFieldPos = $linkedFieldCounter;
							else :
								echo '<td>', $customFieldValue, '</td>';
							endif;
							$linkedFieldCounter++;
						endforeach;
					echo '</tr>';
				endforeach;
			echo '</tbody></table>';
			?>
			<script type="text/javascript">
				// Store Commonly manipulated DOM nodes as objects
				nForm = jQuery('#<?php echo $id; ?>');
				nFormTask = jQuery('input[name="web_apper_task"]', nForm);
				nModal = jQuery('.modal', nForm);
				nModalHeader = jQuery('.modal-header h3', nModal)
				nModalBody = jQuery('.modal-body', nModal);
				nModalClose = jQuery('.modal-footer [data-dismiss="modal"]', nModal)
				nModalSaveBtn = jQuery('.modal-footer #save', nModal)
				nModalUpdateBtn = jQuery('.modal-footer #update', nModal)
				nModalDeleteBtn = jQuery('.modal-footer #delete', nModal)
				nModalElements = jQuery('.modal-body>*', nModal);
				nDeleteWarning = jQuery('#deleteWarning', nModal);
				nTable = jQuery('#<?php echo $id; ?>_datatable');
				
				jQuery(document).ready(function($) {
					// Initialize dataTable
					oTable = $(nTable).dataTable({
						<?php
							if ( !$widget ) :
								// Build the sDom parameter for dataTables
								if( $editor == 'true' )
									$E = 'E';
								global $template;
								if ( stristr($template, 'fullwidth') ) :
									$spanA = 6; $spanB = 6;
								else :
									$spanA = 4; $spanB = 5;
								endif;
								echo "'sDom': \"<'row'<'span".$spanA."'".$E."C><'span".$spanB."'fl>r>t<'row'<'span".$spanA."'i><'span".$spanB."'p>>\",\n";
							else :
								echo "'sDom': \"<'row'r>t<'row'<'span6'p>>\",";
							endif;
						?>
						'sPaginationType': 'bootstrap',
						'oLanguage': {
							'sLengthMenu': 'records per page <select>'+
							'<option value="10">10</option>'+
							'<option value="20">20</option>'+
							'<option value="30">30</option>'+
							'<option value="40">40</option>'+
							'<option value="50">50</option>'+
							'<option value="100">100</option>'+
							'</select>'
						},
						'aoColumnDefs': [ { 'bVisible': false, 'aTargets': [ 0, <?php echo $columnsToHide; ?> ] } ],
						'oColVis': {
							'buttonText': 'Columns',
							'bRestore': true,
							'sAlign': 'left',
							'sSize': 'css',
							'aiExclude': [ 0, <?php echo $linkedFieldPos; ?> ]
						},
					});
					// Add a click handler to the linked cells
					oTable.on('hover', "tbody td.linked-field", function( e ) {
						if ( $(this).attr('id') ) {
							var contents = $(this).html();
							contents = '<a href="' + $(this).attr('id') + '">' + contents + '</a>';
							$(this).html( contents ); 
						}
					});
					// Add a click handler for the Editor Delete row button 
					$('#delete_<?php echo $id; ?>_datatable').on("click", function() {
						$('.modal-body [required]:input', nModal).each( function() {  // Disable required inputs so that form submission does throw an error
							$(this).attr('disabled', '');
						});
					});
	
				});
				// Handle response from ajax post
				function parseResponse<?php echo $id; ?>(response) {
console.log(response);
					var result = jQuery.parseJSON(response);  // Parse response
					if ( result.success ) {  // If ajax returns a successful save
						if ( result.task == 'add' ) {  // If we added a row
							jQuery('input[name="web_apper_id"]', nForm).val( result.ID );  // Insert the returned post ID into the form before getting form values
							var formValues = nForm.getFormValues();  // Get array of form values
							var oRow = oTable.fnAddDataAndDisplay(formValues);  // Add row to table
							<?php if ( $linkedFieldPos ) : // If there is a linked dataTable cell ?>
							var nTr = jQuery(oRow.nTr); // Get the row that was added,
							var nTd = oTable.fnGetTd( nTr[0], <?php echo $linkedFieldPos; ?> );  // and the visble position of the cell,
							jQuery(nTd).attr( 'id', result.url ).addClass('linked-field');  // and link the cell to the record.
							<?php endif; ?>
							nForm.clearForm();  // Clear form values
						} else if ( result.task == 'update' ) {  // If we updated a row
							var rowPosition = oTable.fnGetPosition( jQuery('tr.row_selected')[0] );  // Get the position of the currently selected row
							var formValues = nForm.getFormValues();  // Get array of form values
							oTable.fnUpdate( formValues, rowPosition ); // Update the dataTable row
						} else if ( result.task == 'delete' ) {  // If we deleted a row
							nDeleteWarning.css('display', 'none');  // Hide the delete warning
							nModalDeleteBtn.css('display', 'none');  // Hide the modal submit button
							var rowPosition = oTable.fnGetPosition( jQuery('tr.row_selected')[0] );  // Get the position of the currently selected row
							oTable.fnDeleteRow( rowPosition );  // Delete the row
							jQuery('.modal-body [required]:input', nModal).each( function() {  // Re-enable any required inputs
								jQuery(this).removeAttr('disabled');
							});
						}
					}
					resetModalButtons();
					nModalBody.prepend(result.htmlalert);  // Show and alert
				}
			</script>
            <?php

		// Configure form settings
			$this->config_form( $atts );  // Check if user has proper privileges

		// Build the form			
			$form = new \PFBC\Form($id);
			$form->configure( $this->formConfig );
			$form->addElement(new \PFBC\Element\Hidden('web_apper_form', $id));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_nonce', wp_create_nonce( 'WebApperAwesomeness!87' )));
			$form->addElement(new \PFBC\Element\Hidden('action', 'web_apper' . $this->shortcode));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_task', 'add'));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_fields', $fieldIDs));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_posttype', $posttype));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_titlefield', $titlefield));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_singleviewurl', $singleviewurl));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_success_save', $successsave));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_success_update', $successupdate));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_success_delete', $successdelete));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_failure_save', $failuresave));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_failure_update', $failureupdate));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_failure_delete', $failuredelete));
			// Form Modal header
			$form->addElement(new \PFBC\Element\ModalHeading($posttype));
			$form->addElement(new \PFBC\Element\HTML('<div id="deleteWarning"><span class="label label-important pull-left">Delete ' . $posttype . '</span><p>&nbsp;You are about to delete a ' . $posttype . '. Are you sure you want to do this?</p></div>'));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_id'));
			// Form Modal body
			foreach ( $this->fields as $field ) :
				$this->add_form_field( $field, $form );
			endforeach;
			// Form Modal footer
			$form->addElement(new \PFBC\Element\Button('Save', 'submit', array(
				'id' => 'save',
				'data-loading-text' => 'Saving...'
			)));
			$form->addElement(new \PFBC\Element\Button('Update', 'submit', array(
				'id' => 'update',
				'data-loading-text' => 'Updating...'
			)));
			$form->addElement(new \PFBC\Element\Button('Delete', 'submit', array(
				'id' => 'delete',
				'class' => 'btn btn-danger',
				'data-loading-text' => 'Deleting...'
			)));
            $form->render();  // Output the form

	}

    /**
     * Checks if a shortcode has required attributes
     *
	 * @param string $usercap
     * @since 1.0
     */
	protected function has_req_attrs( $atts ) {
		// Check for required shortcode attributes
		if ( $atts['id'] == null )
			return 'You must give the shortcode a unique ID, i.e., [shortcode id=\'form-1\']';
		if ( $atts['posttype'] == null )
			return 'You must specify the cutom post type to display in the indextable, i.e., [indextable posttype=lead]';
		if ( $atts['fieldset'] == null && $atts['include'] == null )
			return 'You must specify the \'fieldset\' or \'include\' attribute so you have some fields the indextable, i.e., [indextable fieldset=\'group_1\']';
		if ( $atts['titlefield'] == null && $atts['editor'] == 'true' )
			return 'You have the editor enabled. You must specify a field to use for the post title, i.e., [form titlefield=\'field-id]\'';
		return true;
	}

    /**
     * Add new record
     *
     * @since 1.0
     */
	public function add_record() {
		// Add new post
		$title = $this->setTitle();
		$author = $this->setAuthor();
		$new_post = array(  // Create post object
			'post_title'    => trim($title),
			'post_content'  => 'See Custom Fields.',
			'post_type'      => $_POST['web_apper_posttype'],
			'post_status'   => 'publish',
			'post_author'   => $author,
		);
		$postID = wp_insert_post( $new_post );  // insert the post into the database
		
		
		
		
		$user_name = trim($title);
		$userID = username_exists( $user_name );
		if ( $userID !== null ) {
			$append = 1;
			while( $userID !== null ) {
				$append++;
				$user_name .= $append;
				$userID = username_exists( $user_name  );
			}
		}
		$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
		$user_email = $random_password.'@testing.com';
		if ( email_exists($user_email) == false ) {
			$userID = wp_insert_user( array ('user_login' => $user_name, 'user_pass' => $random_password, 'role' => 'client' ) ) ;
		} else {
			return $this->sendResponse( $_POST['web_apper_failure_save'], 'alert-error', 'Oh snap!', false );  // Send Response
		}
		add_user_meta( $userID, 'postID', $postID, true );
		add_post_meta( $postID, 'userID', $userID, true );
	
		// If post was created successfully
		if ( $postID ) :
			
			update_post_meta( $postID, 'phonelead', true );
		
			$this->update_custom_fields_by_id( $postID, $_POST['web_apper_fields'] );  // Save post meta
			return $this->sendResponse( $_POST['web_apper_success_save'], 'alert-success', 'Hurray!', true, $postID, $_POST['web_apper_singleviewurl'] . '?postID=' . $postID );  // Send Response
		else :  // Else post not created
			return $this->sendResponse( $_POST['web_apper_failure_save'], 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Update a record
     *
     * @since 1.0
     */
	public function update_record() {
		// Create post update array
		if ( $_POST['web_apper_id'] ) :
			$this->update_custom_fields_by_id( $_POST['web_apper_id'], $_POST['web_apper_fields'] );  // Save post meta
			return $this->sendResponse( $_POST['web_apper_success_save'], 'alert-success', 'Hurray!', true, $postID, $_POST['web_apper_singleviewurl'] . '?postID=' . $postID );  // Send Response
		else :  // Else post ID missing
			return $this->sendResponse( $_POST['web_apper_failure_save'], 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Delete a record
     *
     * @since 1.0
     */
	public function delete_record() {
		$result = wp_delete_post( $_POST['web_apper_id'] );
		if ( $result ) :	
			return $this->sendResponse( $_POST['web_apper_success_delete'], 'alert-success', 'Hurray!', true );  // Send response
		else :
			return $this->sendResponse( $_POST['web_apper_failure_delete'], 'alert-error', 'Oh snap!', false );  // Send response
		endif;
	}
	
}

$initialize = new RecordIndexPhoneStaff(); 

?>